package com.czl.module_service.viewmodel.assetUse

import android.os.Bundle
import android.util.Log
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.config.AppConstants
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.tengyun.AddApplySortBean
import com.czl.base.data.bean.tengyun.AssetHandleFacilityBean
import com.czl.base.data.bean.tengyun.PurchaseOrderBean
import com.czl.base.data.bean.tengyun.SortBean
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.czl.module_service.adapter.asset.UsageSortChoosedAdapter
import java.util.ArrayList

class UsageApplyAddViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    var list : MutableList<SortBean> = arrayListOf()
    var currentPage = 1
    val uc = UiChangeEvent()
    var sortBean : SortBean? = null
    var note = ObservableField("")
    var businessType = 1
    var adapter : UsageSortChoosedAdapter? = null

    class UiChangeEvent {
        val loadCompleteEvent: SingleLiveEvent<MutableList<SortBean>> = SingleLiveEvent()
        val roleCompleteEvent: SingleLiveEvent<List<Any?>> = SingleLiveEvent()
        val clearFacilityListEvent: SingleLiveEvent<Int> = SingleLiveEvent()
    }

    val addSortLayout: BindingCommand<Any> = BindingCommand(BindingAction {
        getSortList()
    })

    val choosePurchaseOrder: BindingCommand<Any> = BindingCommand(BindingAction {
        startContainerActivity(AppConstants.Router.Service.F_SERVICE_PURCHASE_ORDER_CHOOSE)
        /*startContainerActivity(
            AppConstants.Router.Service.F_SERVICE_PURCHASE_ORDER_CHOOSE
            , Bundle().apply {
                putIntegerArrayList("facilityIdList", facilityIdList)
            })*/
    })

    val addUsageSort : BindingCommand<Any> = BindingCommand(BindingAction {
        addUseApplication()
    })

    fun getSortList() {
        val list1 : MutableList<SortBean> = arrayListOf()
        list1.add(SortBean())
        uc.loadCompleteEvent.postValue(list1)
    }

    fun getRoleProcessList() {
        model.mTengYunHttpDataSource.getRoleProcessList(
            GsonUtils.toJson(
                mapOf(
                    "userId" to model.getLocalUserInfo()?.userId,
                    "companyId" to model.getLoginCompanyId()?.toInt(),
                    "businessId" to 2
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<List<Any?>>>() {
                override fun onResult(t: BaseBean<List<Any?>>) {
                    if (t.state == 0) {
                        uc.roleCompleteEvent.postValue(t.data)
                    } else {
                        showErrorToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    // 新增领用申请
    private fun addUseApplication() {
        val data = adapter?.data
        list = adapter?.data!!
        Log.e("viewModel", "data:" +data?.size)
        val filterList = list.filter { it. sortId != null }
        if (note.get().isNullOrEmpty()) {
            showNormalToast("请填写领用原因")
            return
        }
        if (filterList.isEmpty()) {
            showNormalToast("请选择物品")
            return
        }
        val filterList2 = filterList.filter { it.sortNum == 0 }
        if (filterList2.isNotEmpty()) {
            showNormalToast("物品数量不能为0")
            return
        }
        val list : MutableList<AddApplySortBean> = arrayListOf()
        filterList.forEach {
            val bean = AddApplySortBean()
            bean.id = it.sortId
            bean.name = it.sortName
            bean.count = it.sortNum
            bean.type = 2
            bean.sortModel = it.sortModel
            bean.applyNum = it.sortNum
            bean.price = it.price
            bean.otherValue = it
            bean.otherValue?.count = it.sortNum!!
            list.add(bean)
        }
        model.mTengYunHttpDataSource.addUseApplication(
            GsonUtils.toJson(
                mapOf(
                    "userId" to model.getLocalUserInfo()?.userId,
                    "companyId" to model.getLoginCompanyId()?.toInt(),
                    "note" to note.get(),
                    "workId" to "1",
                    "list" to list,
                    "applicationType" to 0,
                    "businesstype" to businessType
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.state == 0) {
                        showNormalToast("新增成功")
                        uc.clearFacilityListEvent.postValue(0)
                        LiveBusCenter.postGoToTabEvent(1)
                    } else {
                        showErrorToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

}